<template>
  <a-layout-header :style="{backgroundColor:'#ffffff',position: 'fixed', zIndex: 1, width: '100%'}">
    <a-row>
      <a-col :span="4">
        <router-link to="/">
          <a-image :width="60" :preview="false" :src=logoImg></a-image>
        </router-link>
      </a-col>
      <a-col :span="16">
        <a-row>
          <a-col :span="4">
<!--            //TODO 占位1-->
          </a-col>
          <a-col :span="16">
            <a-input-search :style="{marginTop: '18px'}"
                            v-model:value="searchValue"
                            enter-button
                            placeholder="买、买、买！"
                            allowClear
                            size="large"
                            @search="goSearchInfo"
            />
          </a-col>
          <a-col :span="4">
            <!--            //TODO 占位2-->
          </a-col>
        </a-row>

      </a-col>
      <a-col :span="4">
        <div v-if="loginStatus" style="margin-top: 5px">
          <a-row justify="space-around" >
            <a-col :span="4">
              <a @click="goToIMcenter()">
                <message-outlined :style="{fontSize: '25px'}"/>
              </a>
            </a-col>
            <a-col :span="4">
              <router-link to="/shop-car/getOrderItems/">
                <ShoppingOutlined :style="{fontSize: '25px'}"/>
              </router-link>
            </a-col>
            <a-col :span="4">
              <router-link to="/shop-car">
                <a-popover style="min-width: 160px" placement="bottom" title="ShopCar" trigger="hover">
                  <template #content>
                    <div style="max-height: 400px;overflow-y: scroll">
                      <p v-for="carItem in shopCarItems">
                          <a-list :bordered="true" item-layout="horizontal" :data-source="[carItem]">
                            <template #renderItem="{ item }">
                              <a-list-item>
                                <a-list-item-meta
                                    :description=item.price
                                >
                                  <template #title>
                                    <a href="https://www.antdv.com/">{{ item.skuName }}</a>
                                  </template>
                                  <template #avatar>
                                    <a-avatar :src=item.skuDefaultImg />
                                  </template>
                                </a-list-item-meta>
                              </a-list-item>
                              <a-list-item>
                                <template #actions>
                                  <a key="list-loadmore-edit"><DeleteOutlined /></a>
                                </template>
                              </a-list-item>
                            </template>
                          </a-list>
                      </p>
                    </div>
                  </template>
                  <a-badge :count=shopcarItemsCount :style="{fontSize: '10px', marginTop: '8px'}">
                    <ShoppingCartOutlined :style="{fontSize: '25px'}"/>
                  </a-badge>
                </a-popover>
              </router-link>
            </a-col>
            <a-col :span="4">
              <UserOutlined :style="{fontSize: '25px'}" @click="goToUserInfo"/>
            </a-col>
            <a-col :span="4">
              <LogoutOutlined :style="{fontSize: '25px'}" @click="logout"/>
            </a-col>
          </a-row>
        </div>
        <a-typography-text strong v-if="!loginStatus">
          <router-link to="/login">
            登录
          </router-link>
          /
          <router-link to="/register">
            注册
          </router-link>
        </a-typography-text>
      </a-col>
    </a-row>
  </a-layout-header>
</template>

<script setup>
import { ShoppingCartOutlined, LogoutOutlined, UserOutlined, DeleteOutlined,ShoppingOutlined, MessageOutlined} from '@ant-design/icons-vue';
import logoImg from '@/assets/logo.png'
import {ref, onMounted, onBeforeUnmount, watch, onBeforeMount} from 'vue'
import router from '@/router'
import {publish, subscribe, unsubscribe} from "pubsub-js";
import request from "@/utils/request";
import {message} from "ant-design-vue";
import {useSocketStore} from "@/utils/websocket";
import {serverHost, serverPort, wsPath} from "@/utils/constant";

const emit = defineEmits(['sendRoutes', 'sendSearchText', 'getLoginStatus', 'shopcarItems'])
let searchValue = ref('')
let routes = ref('')
let shopcarItemsCount = ref(0)
let userSession = ref(null)

let loginStatus = ref(false)
//判断登录状态
loginStatus.value = localStorage.getItem('loginStatus') !== null && localStorage.getItem('loginStatus') === 'logging'

const shopCarItems = ref([])

watch(routes, (newVal, oldVal) => {
  //订阅 home-sideBar的发布
  //向父组件传值
  emit('sendRoutes', newVal)
})

let logoutPubId = subscribe("logout", (msg,data)=>{
  loginStatus.value = false
  emit('getLoginStatus',loginStatus.value)
  unsubscribe(logoutPubId)
})

let pubId = subscribe('addItem', (msg,data) => {
  //订阅添加商品事件
  getShopcarItems()
})

let delOne_pubId = subscribe(['delItem'], (msg, data) => {
  //订阅删除购物项事件
  getShopcarItems()
})

  function logout(){
    request({
      url: '/auth/logout',
      method: 'get',
    }).then(res=>{
      if(res.code === 200){
        message.info('您已登出')
        publish("logout","登出")
        loginStatus.value = false
        localStorage.removeItem('token')
        localStorage.removeItem('session')
        router.push({path: '/'})
      }else {
        message.info('登出失败'+res.msg)
        router.push({
          path: '/login'
        })
      }
    }).catch(err=>{
      message.error('登出异常'+err.messages)
    })
    if (typeof useSocketStore().closeWs !== "undefined") {
      useSocketStore().closeWs()
    }
  }

  function goSearchInfo(value){
    if(typeof value !== "undefined" && value !== null && value !== ''){
      emit('sendSearchText', value)
      router.push({
        path: "/product/search",
        query: {
          searchText: value
        }
      })
    }
  }

  function goToUserInfo(){
    // TODO 前往个人中心
    router.push({
      path: '/userinfo'
    })
  }

  const getShopcarItems = ()=>{
    //获取购物车数据
    let skuIds = []
    request({
      url: '/auth/user/shop-car/getCartIems',
      method: 'get',
    }).then(res =>{
      if(res.code === 0){
        shopcarItemsCount.value = res.data.length
        res.data.forEach(item => {
          skuIds.push(item.skuId)
          shopCarItems.value.push(item)
        })
        emit("shopcarItems", res.data)
      }else {
        console.log(res.code, res.msg)
        message.info(res.msg)
        //loginStatus.value=false
      }
    }).catch(err => {
      console.log("获取购物车数据失败", err.message)
      message.error(err.message)
    })
  }

  const getSession =()=>{
    if(loginStatus.value) {
      // 询问 session 信息
      request({
        url: '/auth/user/get-loginInfo',
        method: 'get'
      }).then(res => {
        if(res.code === 0){
          userSession.value = res.data
          //publish('session', res.data)
          localStorage.setItem('session', JSON.stringify(res.data))
        }else {
          console.log('服务端获取session异常', res.msg)
          message.error(res.msg)
        }
      }).catch(err => {
        console.log('获取session异常', err.message)
      })

    }
  }

  const goToIMcenter=()=>{
    let param = userSession.value.mobile !==null ? userSession.value.mobile : userSession.value.email
    router.push({
      name: 'friendList',
      params: {userId: param}
    })
  }

  onBeforeMount(_=>{
    getSession()
    getShopcarItems()
    //ws实例检测
    if(typeof useSocketStore().ws === "undefined") {
      let session = JSON.parse(localStorage.getItem('session'))
      if(typeof session !== "undefined" && session !== null) {
        console.log('ws重新创建', session)
        useSocketStore().sendMsgParam.fromId = session.id
        const ws = useSocketStore()
        useSocketStore().sendMsgParam.type = 0
        ws.connection(`ws://${serverHost}:${serverPort}${wsPath}`)
      }
    }
  })

  onMounted(()=>{
    searchValue.value = router.currentRoute.value.query.searchText
    emit('sendSearchText', searchValue.value)
    emit('getLoginStatus', loginStatus.value)
    subscribe('routes', (_,data)=>{
      routes.value = data
    })
  })

  onBeforeUnmount(()=>{
    unsubscribe(pubId)
    unsubscribe(delOne_pubId)
  })

</script>